
import { useEffect, useState } from "react";
import { Card, Form, Input, Button, Table, Select, Row, Col, message } from "antd"
  ;
import { SearchOutlined } from "@ant-design/icons";

// import type { ColumnsType } from "antd/lib/table";

import { useNavigate } from "react-router-dom";

//引入请求
import {
  getHospitalListRequest,
  getProvinceRequest,
  getCityOrAreaRequest,
  onUnderRequest
} from '@api/hospital/hospitalListSet'

import type {
  hospitalListContentType,
  getProvinceReturnType,
  getHosListSearchParamsType
} from '@api/hospital/model/hospitalListTypes'
import { useForm } from "antd/lib/form/Form";

const { Option } = Select;



export default function HospitalList() {

  //路由跳转
  const navigate = useNavigate()
  //定义form
  const [form] = useForm()
  //定义当前页面按钮第几个的状态
  const [page, setPage] = useState(1)
  //定义限制列表数据条数的状态
  const [limit, setLimit] = useState(3)
  //定义查询参数的状态
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>({})
  //定义加载数据的状态
  const [tableData, setTableData] = useState<hospitalListContentType>([])
  //定义缓冲 是否在加载中
  const [isLoading, setIsLoading] = useState(false)
  //定义保存省份数据
  const [province, setProvince] = useState<getProvinceReturnType>([])
  //定义保存市区份数据
  const [cityOrArea, setCityOrArea] = useState<getProvinceReturnType>([])
  //定义保存市区份数据
  const [Area, setArea] = useState<getProvinceReturnType>([])
  //定义医院类型状态
  const [hosType, setHosType] = useState<getProvinceReturnType>([])
  //定义重新渲染状态
  const [reRender, setRerender] = useState(false)

  //初始化获取列表
  useEffect(() => {
    (async () => {
      setIsLoading(true)
      const result = await getHospitalListRequest(
        page,
        limit,
        searchParams)
      setTableData(result.content)
      setIsLoading(false)
    })()
  }, [page, limit, searchParams, hosType, reRender])
  //初始化获取省份
  useEffect(() => {
    (async () => {
      const result = await getProvinceRequest()
      setProvince(result)
    })()
  }, [])

  //3.控制医院类型
  useEffect(() => {
    (async () => {
      const result = await getCityOrAreaRequest(10000)
      //获取医院类型
      setHosType(result)
    })()
  }, [])

  /* 
  onChange = { changeProviceHandle }
  changeProviceHandle(a, b)
  a 140000 
  b {key: '140000', value: '140000', children: '山西省', id: 140000}  
  */

  //事件函数
  const changeProviceHandle = async (id: number) => {
    const re = await getCityOrAreaRequest(id)
    setCityOrArea(re)
    //在切换省份的时候要将其他的输入框清空
    form.setFieldsValue({ cityCode: null, districtCode: null })
    //选完市之后把县清空
    //清空区的数据
    setArea([])
  }
  const changeCityHandle = async (id: number) => {
    const re = await getCityOrAreaRequest(id)
    setArea(re)
    //清空上一次区的数据 不然就一直不变
    form.setFieldsValue({ districtCode: null });
  }

  //表单收集函数
  const searchHosFinishHandle = (value: getHosListSearchParamsType) => {
    setSearchParams(value)
  }
  //搜索清空按钮
  const killHosFinishHandle = () => {
    setSearchParams({})
  }

  //跳转医院详情函数
  const goHospitalDetail = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalShow${id}`)
    }
  }
  //跳转医院排版函数
  const goHospitalCheck = (hoscode:string) => {
    return () => {
      navigate(`/syt/hospital/hospitalCheck${hoscode}`)
    }
  }

  //上下线按钮函数
  const onUnderHnadle = (id: string, status: 0 | 1) => {
    return async () => {
      await onUnderRequest(id, status)
      message.success("更改上线成功")
      setRerender(!reRender)
    }
  }




  const columns = [
    {
      title: '序号',
      render(_: any, __: any, index: number) {
        // console.log(index)
        return index + 1
      },
      dataIndex: 'index',
      width: 60
    },
    {
      title: '医院log',
      dataIndex: 'logoData',
      render(logo: string) {
        return <div>
          <img width={100} src={`data:image/jpeg;base64,${logo}`} alt="医院Log" />
        </div>
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      dataIndex: 'apiUrl',
      render(_: any, data: any) {
        return <div>
          <div>
            {/* data中有要的等级 */}
            {data.param.hostypeString}
          </div>
        </div>
      }
    },
    {
      title: '地址',
      dataIndex: 'fullAddress',
      render(_: any, data: any) {
        return <div>
          <div>
            {data.param.fullAddress}
          </div>
        </div>
      }
    },
    {
      title: '状态',
      dataIndex: 'contactsName',
      render(_: any, data: any) {
        return <div>
          <div>
            {data.status ? "上线" : "下线"}
          </div>
        </div>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'contactsPhone',
      render(_: any, data: any) {

        return <div>
          <div>
            {data.createTime}
          </div>
        </div>
      }
    },
    {
      title: '操作',
      fixed: "right" as "right",
      render(data: any) {
        // console.log(data);
        return (
          <div>
            <Button
              onClick={goHospitalDetail(data.id)}
              type='primary'
            >查看</Button>
            <Button
              onClick={goHospitalCheck(data.hoscode)}
              type='primary'
            >排班</Button>
            <Button
              /*
              点击按钮发送改变医院状态请求
              根据接口需要 id和status
              //根据数据中的status是否等于0来判断要发送 1 还是 0 下次再发送不同的 达到切换效果
                */
              onClick={onUnderHnadle(data.id, data.status === 0 ? 1 : 0)}
              type='primary'>
              {/* 因为按钮的状态应该与医院真实状态反过来所以取反发过来的值*/}
              {
                !data.status ? "上线" : "下线"
              }</Button>
          </div >
        )
      }
    }
  ];




  return (
    <Card>
      <Form
        form={form}
        onFinish={searchHosFinishHandle}
      >
        <Row gutter={30}>

          <Col span={4}>
            <Form.Item
              name="provinceCode"
            >
              <Select
                placeholder="请选择省"
                onChange={changeProviceHandle}
              >
                {
                  province.map(item => <Option value={item.value} id={item.id} key={item.id}>{item.name}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="cityCode">
              <Select
                placeholder="请选择市"
                onChange={changeCityHandle}
              >
                {
                  cityOrArea.map(item => <Option value={item.value} id={item.id} key={item.id}>{item.name}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="districtCode">
              <Select placeholder="请选择区">
                {
                  Area.map(item => <Option value={item.value} id={item.id} key={item.id}>{item.name}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="hosname">
              <Input placeholder="医院名称" />
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="hoscode">
              <Input placeholder="医院编号" />
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item className="mt" name="hostype">
              <Select placeholder="医院类型">
                {
                  hosType.map(item => <Option value={item.value} id={item.id} key={item.id}>{item.name}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>

        </Row>


        <Row gutter={30} >

          <Col span={4}>
            <Form.Item name="status">
              <Select placeholder="医院状态">
                <Option value={0}>未上线</Option>
                <Option value={1}>已上线</Option>
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item>
              <Button
                // onClick={searchParamsHandle}
                type="primary"
                icon={<SearchOutlined />}
                htmlType="submit">
                查询
              </Button>
              <Button
                onClick={killHosFinishHandle}
                style={{ marginLeft: 20 }}
              >
                清空
              </Button>
            </Form.Item>
          </Col>

        </Row>

      </Form>

      <Table

        columns={columns}
        dataSource={tableData}
        //列表边框
        bordered
        //横向滚动条
        scroll={{ x: 1400 }}
        //给列表的每一项添加一个hoscode作为Key
        // rowKey={"hoscode"}
        rowKey="id"
        //页码加载等待状态
        loading={isLoading}
        // 页码的配置：
        pagination={{
          // 页码的配置：当前的页码
          current: page,
          // 总数据的数量
          total: 15,
          // 每页条数
          pageSize: limit,
          // 展示更改每页条数的选项（默认total大于条的时候开启）
          pageSizeOptions: [3, 6, 9, 15],
          // 是否直接开启更新每页条数的选项
          showSizeChanger: true,
          onChange(page, pageSize) {
            //第几页
            setPage(page)
            //每页条数
            setLimit(pageSize)
          },
          showTotal(total) {
            return `总共有${total}数据`
          }
        }}
      />

    </Card>
  )
}
